import {isDevelopment, logger} from "../utils";
import * as process from "node:process";

let db: { query: (arg0: string, arg1?: any[]) => PromiseLike<[any]> | [any]; };
export default (c: any) => {
  db = c
  if(!isDevelopment() && process.env.DB_HEARTBEAT === "true"){
    Heartbeat()
  }
};

// 定期发送心跳查询
function Heartbeat() {
  let cnt = 0;
  setInterval(async () => {
    try {
      await db.query("SELECT 1");
      cnt++;
      if(process.env.DB_HEARTBEATLOG === "true"){
        logger("Heartbeat sent to keep the connection alive."+ cnt);
      }
    } catch (err) {
      logger("Heartbeat query failed:", err);
    }
  }, process.env.DB_HEARTBEATTIME as any);
}

export function createSql<T = any>(sql: string, query = []): Promise<T> {
  return new Promise(async (resolve, reject) => {
    try {
      const [r] = await db.query(sql, query);
      return resolve(r);
    } catch (err) {
      return reject(err);
    }
  });
}
